package com.bss.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.andy.basics.Service;
import com.bss.model.DailyRevenue;
import com.bss.model.Payment;
import com.bss.model.Revenue;
import com.bss.model.RevenueHead;
import com.bss.service.DailyRevenueService;

@Controller
@Scope("request")
public class DailyRevenueController extends com.andy.basics.Controller<DailyRevenue> {

	@Autowired
	private DailyRevenueService dailyRevenueService;

	@Override
	public Service<DailyRevenue> getService() {
		return this.dailyRevenueService;
	}

	@Override
	public DailyRevenue create() {
		DailyRevenue dailyRevenue = new DailyRevenue();
		dailyRevenue.setTotal(0);
		for (RevenueHead revenueHead : this.dailyRevenueService
				.getRevenueHeads()) {
			Revenue revenue = new Revenue();
			revenue.setRevenueHead(revenueHead);
			revenue.setAmount(0);
			dailyRevenue.getRevenues().add(revenue);
		}
		dailyRevenue.setPayments(this.dailyRevenueService
				.getPayments(dailyRevenue.getDate()));
		dailyRevenue.setPaymentTotal(0);
		if (dailyRevenue.getPayments() != null) {
			for (Payment payment : dailyRevenue.getPayments()) {
				dailyRevenue.setTotal(dailyRevenue.getTotal()
						+ payment.getAmount());
				dailyRevenue.setPaymentTotal(dailyRevenue.getPaymentTotal()
						+ payment.getAmount());
			}
		}
		if (this.dailyRevenueService.getLastActivity() != null) {
			dailyRevenue.setLastReportGeneratedDate(this.dailyRevenueService
					.getLastActivity().getActivityDate());
		}
		return dailyRevenue;
	}

	public void doTotal() {
		DailyRevenue dailyRevenue = getModel();
		dailyRevenue.setTotal(0);
		for (Revenue revenue : dailyRevenue.getRevenues()) {
			dailyRevenue
					.setTotal(dailyRevenue.getTotal() + revenue.getAmount());
		}
		dailyRevenue.setPayments(this.dailyRevenueService
				.getPayments(dailyRevenue.getDate()));
		dailyRevenue.setPaymentTotal(0);
		if (dailyRevenue.getPayments() != null) {
			for (Payment payment : dailyRevenue.getPayments()) {
				dailyRevenue.setTotal(dailyRevenue.getTotal()
						+ payment.getAmount());
				dailyRevenue.setPaymentTotal(dailyRevenue.getPaymentTotal()
						+ payment.getAmount());
			}
		}
	}

	@Override
	public String add() {
		DailyRevenue dailyRevenue = getModel();
		for (Revenue revenue : dailyRevenue.getRevenues()) {
			revenue.setDateOfIncome(dailyRevenue.getDate());
		}
		return super.add();
	}

}